let { getTime } = require("./../../utils/constant.js");
let { api } = require("./../../utils/api.js");
Page({
  data: {
    date: getTime(),
    titleArr: ["荤菜", "素菜", "点心", "水果"],
    searchData: true
  },

  onLoad: function() {
    this.getSeventMenu();
  },

  onPullDownRefresh: function() {
    //下拉刷新数据
    this.setData({
      isSearch: false,
      searchData: true
    });
    this.getSeventMenu();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1500);
  },

  //获取最近7日菜单
  getSeventMenu: function() {
    let that = this;
    wx.request({
      url: api + "getHistorytMenu.do",
      method: "GET",
      success: function(res) {
        if (res.data.status === 1) {
          let data = res.data.data;
          let sevenMenus = [];
          for (let i = 0; i < data.length; i++) {
            let obj = {};
            obj.time = data[i].menuDate;
            obj.menus = that.filterMenu(data[i].dishs);
            sevenMenus.push(obj);
          }
          that.setData({
            sevenMenus
          });
        } else {
          that.setData({
            searchData: false
          });
        }
      },
      fail: function(res) {
        console.log(res);
        console.log("获取7日菜单失败！");
      }
    });
  },

  // 将每日的所有菜单筛选成四大类
  filterMenu: function(menuArr) {
    let menu = [
      [], //荤菜集合
      [], //素菜集合
      [], //点心集合
      [] //水果集合
    ];
    for (let i = 0; i < menuArr.length; i++) {
      //后期将菜系评分进行四舍五入保留小数点后一位  如1.2
      //后期进行判断是否是新品 ，是的话设置isNewFood状态
      let category = menuArr[i].dishCategory - 1; //记录该菜系是什么种类
      menu[category].push(menuArr[i].dishName);
    }
    return menu;
  },

  // 查找菜单
  bindDateChange: function(e) {
    let that = this;
    console.log("picker发送选择改变，携带值为", e.detail.value);
    this.setData({
      date: e.detail.value,
      isSearch: true,
      searchData: false
    });
    //查找某个日期菜单
    wx.request({
      url: api + "getTargetMenu.do",
      method: "POST",
      data: {
        menuDate: e.detail.value
      },
      success: function(res) {
        console.log(res.data);
        //此时如果查找后存在数据,渲染结果，否则显示无数据页面
        if (res.data.status === 1) {
          let searchMenus = [
            {
              time: e.detail.value,
              menus: that.filterMenu(res.data.data.dishs)
            }
          ];
          console.log(searchMenus);
          that.setData({
            searchMenus,
            searchData: true
          });
        } else {
          that.setData({
            searchData: false
          });
        }
      },
      fail: function(res) {
        console.log(res);
        console.log("查找菜单失败！");
      }
    });
  }
});
